<template>
  <div class="h-full w-full flex flex-col justify-between">
    <div class="form px-[15px] pt-[15px] border-bottom">
      <el-form>
        <el-row :gutter="12">
          <el-col :span="3">
            <el-form-item>
              <el-select class="!w-full" v-model="form.lottery_id">
                <el-option label="全部游戏" value="-1" />
                <el-option
                  v-for="item in gameTotal"
                  :key="item.LotteryId"
                  :label="item.Name"
                  :value="item.LotteryId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item>
              <el-input v-model="form.issue" placeholder="请输入期号" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <div class="w-full flex justify-between">
                <el-date-picker
                  v-model="form.date"
                  type="daterange"
                  unlink-panels
                  range-separator="－"
                  start-placeholder="选择开始时间"
                  end-placeholder="选择结束时间"
                  :disabled-date="disableFutureDates"
                />
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <div class="flex justify-between">
              <el-form-item>
                <el-button type="primary" @click.stop="search">搜索</el-button>
                <el-button type="danger" @click.stop="handleRefresh">清空</el-button>
                <el-button type="danger" v-if="premsStore.isEditDeleteReport" @click="handleDelete"
                  >删除</el-button
                >
                <el-button type="primary" @click="emit('changeType', 'fail')">
                  飞单失败明细
                </el-button>
              </el-form-item>
              <div class="flex h-[32px] items-center">
                <el-button type="primary" size="small" round @click="getData">刷新</el-button>
                <div class="w-[80px] text-center mx-[10px]">
                  {{ count == 0 ? "手动" : count + "秒" }}
                </div>
                <el-select v-model="flyTimer" size="small">
                  <el-option
                    size="small"
                    v-for="item in timerList"
                    :key="item.value"
                    :label="item.name"
                    :value="item.value"
                  />
                </el-select>
              </div>
            </div>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="grow-[1] h-0 mx-[15px] mt-[10px]">
      <el-table
        scrollbar-always-on
        ref="elTableRef"
        v-loading="state.loading"
        :data="list"
        height="100%"
        border
        stripe
        fit
      >
        <template #empty>
          <ui-empty />
        </template>
        <el-table-column align="center" prop="LotteryName" label="游戏类型" show-overflow-tooltip>
          <template #default="{ row }: TableItem">
            {{ row.LotteryName || "--" }}
          </template>
        </el-table-column>
        <el-table-column align="center" prop="BitchNo" label="游戏期数" show-overflow-tooltip>
          <template #default="{ row }: TableItem">
            {{ row.BitchNo || "--" }}
          </template>
        </el-table-column>
        <el-table-column align="center" prop="Count" label="总注单" show-overflow-tooltip>
          <template #default="{ row }: TableItem">
            {{ row.Count || "--" }}
          </template>
        </el-table-column>
        <el-table-column align="center" prop="Amount" label="总金额" show-overflow-tooltip>
          <template #default="{ row }: TableItem">
            {{ row.Amount || "--" }}
          </template>
        </el-table-column>
        <el-table-column align="center" prop="Status" label="状态" width="70">
          <template #default="{ row }: TableItem">
            <span
              :class="{
                'text-blue': row.Status === 0,
                'text-green': row.Status === 1,
                'text-red': row.Status === 2
              }"
            >
              {{ statusMap[row.Status] }}
            </span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="CreatedAt" label="开奖时间" width="170">
          <template #default="{ row }: TableItem">
            {{ formatDate(row.CreatedAt) || "--" }}
          </template>
        </el-table-column>
        <el-table-column align="center" prop="LuckCode" label="开奖结果" width="380">
          <template #default="{ row }: TableItem">
            <template v-if="row.LuckCode">
              <template v-if="row.CategoryId == GameCategory.lhc">
                <div>
                  <lhc-ball
                    class="!mr-[4px]"
                    :num="num"
                    :key="i"
                    v-for="(num, i) in formatNum(row)"
                  />
                </div>
              </template>
              <template v-if="row.CategoryId == GameCategory.pcdd">
                <div class="flex items-center justify-center">
                  <pcdd-ball class="!ml-[4px]" :num="formatNum(row)?.[0]" />
                  <pcdd-ball class="!ml-[4px]" :num="formatNum(row)?.[1]" />
                  <pcdd-ball class="!ml-[4px]" :num="formatNum(row)?.[2]" />
                  <span class="mx-[4px]">+</span>
                  <pcdd-ball :num="formatCount(row)" />
                </div>
              </template>
              <template v-if="row.CategoryId == GameCategory.sc">
                <div>
                  <sc-ball
                    class="!mr-[2px]"
                    :num="num"
                    :key="i"
                    v-for="(num, i) in formatNum(row)"
                  />
                </div>
              </template>
              <template v-if="row.CategoryId == GameCategory.ssc">
                <div>
                  <ssc-ball
                    class="!mr-[4px]"
                    :num="num"
                    :key="i"
                    v-for="(num, i) in formatNum(row)"
                  />
                </div>
              </template>
            </template>
            <template v-else>
              <div>--</div>
            </template>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="100">
          <template #default="{ row }: TableItem">
            <el-button size="small" type="primary" @click="handleOpenDetail(row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="flex justify-end my-[10px] mx-[15px]">
      <ui-pagination
        :total="state.total"
        v-model:pageSize="state.pageSize"
        v-model:currentPage="state.page"
        @current-change="getData"
      ></ui-pagination>
    </div>
    <DeleteDialog ref="deleteDialogRef" />
  </div>
</template>
<script setup lang="ts">
import DeleteDialog from "./delete-dialog.vue";
import moment from "moment";
import { useList } from "@/hooks/useList";
import { useGameStore } from "@/store/modules/game";
import { storeToRefs } from "pinia";
import { disableFutureDates, formatDate, getDateArray } from "@/utils/common";
import { reqDapanReportList } from "@/api/flyalone";
import { GameCategory } from "@/enums";
import { useTimerStore } from "@/store/modules/timer";
import { usePremsStore } from "@/store/modules/prems";

interface TableItem {
  row: DapanReportMo;
}
interface Params {
  Issue?: string;
  Name?: string;
  Type?: string;
  StartDate?: string;
  EndDate?: string;
  LotteryId?: string;
}

const props = withDefaults(
  defineProps<{
    type: "list" | "detail" | "fail";
  }>(),
  {
    type: "list"
  }
);

let timer: any;
const emit = defineEmits(["changeType", "changeDetail"]);
const gameStore = useGameStore();
const { gameTotal } = storeToRefs(gameStore);
const premsStore = usePremsStore();
const timerStore = useTimerStore();
const { timerList, flyTimer } = storeToRefs(timerStore);
const count = ref(flyTimer.value);
const deleteDialogRef = ref();
const statusMap = reactive<Record<string, string>>({
  0: "等待中",
  1: "成功",
  2: "失败"
});
const form = reactive({
  lottery_id: "-1",
  issue: "",
  date: getDateArray()["today"]
});

const getParams = () => {
  const params: Params = {};
  if (form.issue) {
    params.Issue = form.issue;
  }
  if (form.date) {
    params.StartDate = moment(form.date[0]).format("YYYY-MM-DD 00:00:00");
    params.EndDate = moment(form.date[1]).format("YYYY-MM-DD 23:59:59");
  }
  if (form.lottery_id && form.lottery_id != "-1") {
    params.LotteryId = form.lottery_id;
  }
  return params;
};

const { elTableRef, state, list, getData, search } = useList<DapanReportMo, Params>(
  reqDapanReportList,
  getParams
);
// 重置
const handleRefresh = () => {
  form.lottery_id = "-1";
  form.issue = "";
  form.date = getDateArray()["today"];
  search();
};

const formatNum = (row: DapanReportMo) => {
  return row.LuckCode.split(",").map(Number);
};

const formatCount = (row: DapanReportMo) => {
  return row.LuckCode.split(",")
    .map(Number)
    .reduce((a, b) => a + b, 0);
};

const handleDelete = () => {
  deleteDialogRef.value?.open();
};
const handleOpenDetail = (row: DapanReportMo) => {
  emit("changeDetail", row.Id);
};

const setTimer = () => {
  clearInterval(timer);
  timer = null;
  if (flyTimer.value > 0) {
    timer = setInterval(() => {
      count.value--;
      if (count.value == 0) {
        count.value = flyTimer.value;
        if (props.type == "list") {
          getData();
        }
      }
    }, 1000);
  } else {
    clearInterval(timer);
    timer = null;
    count.value = 0;
  }
};

watch(
  () => flyTimer.value,
  val => {
    count.value = val;
    nextTick(setTimer);
  }
);

onMounted(() => {
  setTimer();
  getData();
});

onUnmounted(() => {
  clearInterval(timer);
  timer = null;
});
defineExpose({
  getData
});
</script>
